package org.swim.session;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swim.entity.User;


@Stateless
@RemoteBinding(jndiBinding="RegistrationManagerRemote")
public class RegistrationManager implements RegistrationManagerRemote {

	/**
	 * Manager degli entity beans. Permette di interagire direttamente col database inserendo e ricercando dati
	 */
	@PersistenceContext(unitName="swim") private EntityManager manager;
	
	@Override
	public int createNewUser(String name, String surname, String mail,
			String password) {
		final String DEFAULT_AVATAR = "http://www.geekitalia.it/wordpress/NoAvatar.jpg";
		User u=new User();
		u.setAdmin(false);			
		u.setCognome(surname);
		u.setEmail(mail);
		u.setNome(name);
		u.setPassword(password);
		u.setAvatar(DEFAULT_AVATAR);
		manager.persist(u);
		
		return u.getId();
		
	}

	
	@Override
	public boolean verifyRegistrationData(String mail) {
		
		try{
			Query q=manager.createQuery("SELECT OBJECT(u) FROM User as u WHERE u.email=:userMail");
			q.setParameter("userMail", mail);
			
			@SuppressWarnings("unchecked")
			Collection<User> coll = (Collection<User>) q.getResultList();
			
			if(coll.isEmpty())
				return true;
			else 
				return false;
		}
		catch(EntityNotFoundException e){}
		
		return false;
		
		
	}

}
